package com.jjshop.ui.homefragmentitem;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jjshop.R;
import com.jjshop.utils.GlobalContanst;
import com.jjshop.utils.JsonUtils;
import com.jjshop.utils.UIUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by apple on 18/6/23.
 */

public class HomeItemFragment extends Fragment {


    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private String id;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle bundle = getArguments();
        id = bundle.getString("id");
        if (TextUtils.isEmpty(id)){
            UIUtils.showToast("数据错误，请重试");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.fragment_home_item,null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refreshLayout = (RefreshLayout)view.findViewById(R.id.refreshLayout);
        recyclerView = view.findViewById(R.id.recyclerView);
        initData();
        loadData(true);
    }

    private void initData(){
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        MyAdapter adapter = new MyAdapter(getContext(),null);
        recyclerView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
    }

    /**
     *   {
     "id":"961",
     "brand_id":"1000057",
     "category_id":"210",
     "supplier_id":"55",
     "name":"【杨艺制造-贝嘉杰】真皮透气浅口高跟凉鞋【WHBJJ】",
     "code":"02023961",
     "stock_num":"694",
     "idcode":"5389nm",
     "price":"158.00",
     "earn_price":"21.20",
     "product_id":"961",
     "has_stock":1,
     "img":"https://pimgds.999d.com/uploads/product/c7d8fca073c3f38d1d734a516ea7b089.jpg?imageView2/1/w/900/h/420/q/75|imageslim"
     },
     * @param isRefresh
     */
    private void loadData(boolean isRefresh){
        OkHttpUtils.get().url(GlobalContanst.JJMAIL_INDEX + "?cid="+id)
                .addHeader(GlobalContanst.COOKIE,GlobalContanst.getCookies(getContext()))
                .addHeader(GlobalContanst.User_Agent,GlobalContanst.getUserAgent(getContext()))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ArrayList<Map<String, String>> listMapByJson = JsonUtils.getListMapByJson(response);
                        String data = listMapByJson.get(0).get("data");
                        ArrayList<Map<String, String>> listMapByJson1 = JsonUtils.getListMapByJson(data);
                        String index_data = listMapByJson1.get(0).get("index_data");
                        ArrayList<Map<String, String>> listMapByJson2 = JsonUtils.getListMapByJson(index_data);
                        String product_list = listMapByJson2.get(0).get("product_list");
                        ArrayList<Map<String, String>> listMapByJson3 = JsonUtils.getListMapByJson(product_list);

                    }
                });
    }


    public static class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        private ArrayList<Map<String,String>> datas;
        private Context context;

        public MyAdapter(Context context,ArrayList<Map<String,String>> datas){
            this.context = context;
            this.datas= datas;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.view_home_item,parent,false);
            ListViewHolder viewHolder = new ListViewHolder(view);

            return viewHolder;
        }



        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ListViewHolder viewHolder = (ListViewHolder) holder;

        }

        @Override
        public int getItemCount() {
            return datas==null? 10 : datas.size();
        }
    }


    public static class ListViewHolder extends RecyclerView.ViewHolder{

        private SparseArray<View> mViewCache = new SparseArray<View>();

        public ListViewHolder(View itemView) {
            super(itemView);
        }


        public void putView(int id) {
            if (itemView != null) {
                mViewCache.put(id, itemView.findViewById(id));
            }
        }

        public View findView(Integer id) {
            return mViewCache.get(id);
        }
    }

//    --------------------------简单使用-------------------------------
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        Banner banner = (Banner) findViewById(R.id.banner);
//        //设置图片加载器
//        banner.setImageLoader(new GlideImageLoader());
//        //设置图片集合
//        banner.setImages(images);
//        //banner设置方法全部调用完毕时最后调用
//        banner.start();
//    }
//--------------------------详细使用-------------------------------
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        Banner banner = (Banner) findViewById(R.id.banner);
//        //设置banner样式
//        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
//        //设置图片加载器
//        banner.setImageLoader(new GlideImageLoader());
//        //设置图片集合
//        banner.setImages(images);
//        //设置banner动画效果
//        banner.setBannerAnimation(Transformer.DepthPage);
//        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
//        //设置自动轮播，默认为true
//        banner.isAutoPlay(true);
//        //设置轮播时间
//        banner.setDelayTime(1500);
//        //设置指示器位置（当banner模式中有指示器时）
//        banner.setIndicatorGravity(BannerConfig.CENTER);
//        //banner设置方法全部调用完毕时最后调用
//        banner.start();
//    }
//-----------------当然如果你想偷下懒也可以这么用--------------------
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        Banner banner = (Banner) findViewById(R.id.banner);
//        banner.setImages(images).setImageLoader(new GlideImageLoader()).start();
//    }
//如果你需要考虑更好的体验，可以这么操作
//@Override
//protected void onStart() {
//    super.onStart();
//    //开始轮播
//    banner.startAutoPlay();
//}
//
//    @Override
//    protected void onStop() {
//        super.onStop();
//        //结束轮播
//        banner.stopAutoPlay();
//    }
}
